package gr.idocs.workshop;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
	private static Logger logger = LoggerFactory.getLogger(Main.class);
//	private static String inFilePath1 = "inFile1.txt";
//	private static String inFilePath2 = "inFile2.txt";
	private static String inFilePath1 = "input1.txt";
	private static String inFilePath2 = "input2.txt";
	private static String outFilePath = "outFile.txt";

	public static void main(String[] args) {
		long startTime = System.nanoTime();
		if (validateArguments(args)) {
			inFilePath1 = args[0];
			inFilePath2 = args[1];
			outFilePath = args[2];
		}

		ArrayList<String> inFileSorted1 = getSortedListFromFile(inFilePath1);
		
		ArrayList<String> inFileSorted2 = getSortedListFromFile(inFilePath2);

		mergeListsToFile(inFileSorted1, inFileSorted2, outFilePath);
		long endTime = System.nanoTime();
		long duration = endTime - startTime;
		logger.info("Approximate Method Execution Time: " + duration / 1000000000F);
	}

	/*
	 * Call the retainAll method of List that keeps in the caller list only the elements that are also in the argument
	 * List. Then write the List to disk.
	 */
	public static void mergeListsToFile(ArrayList<String> inFileSorted1, ArrayList<String> inFileSorted2,
			String outFilePath) {
		inFileSorted1.retainAll(inFileSorted2);
		try {
			FileUtils.writeLines(new File(outFilePath), inFileSorted1);
		} catch (IOException e) {
			logger.error("An error occured while writing the file :" + outFilePath);
		}
	}

	/*
	 * Read the file to an ArrayList and sort it by the default collection sorter (happens to be lexicographically
	 * correct)
	 */
	public static ArrayList<String> getSortedListFromFile(String filePath) {
		ArrayList<String> list = new ArrayList<String>();
		try {
			list = (ArrayList<String>) FileUtils.readLines(new File(filePath));
			Collections.sort(list);
		} catch (IOException e) {
			logger.error("An error occured while reading the file: " + filePath);
		}
		return list;
	}

	/*
	 * If an argument is found that is not a valid file path, or it is a path to a file that does not exist the method
	 * returns false.
	 */
	public static boolean validateArguments(String[] args) {
		boolean result = true;
		if (args.length != 3) {
			logger.info("Wrong number of arguments given. The default file paths will be used.");
			result = false;
		} else {
			for (int i = 0; i < args.length; i++) {

				String path = FilenameUtils.getPath(args[i]);
				if (path == null || path.equals("")) {
					//logger.error("Filepath '" + args[i] + "' does not exist or is invalid.");
					result = false;
				}
			}
		}
		return result;
	}

}
